package org.glut.cloud.repairRecordManage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.glut.cloud.repairRecordManage.MaintenanceRecordsdto.MaintenanceRecordsdto;
import org.glut.cloud.repairRecordManage.entity.MaintenanceRecords;
import org.glut.cloud.repairRecordManage.entity.ResponseResult;
import org.glut.cloud.repairRecordManage.service.IMaintenanceRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 *  前端控制器
 *
 * @author qjc
 * @since 2024-08-13 11:45
 */
@Slf4j
@RestController
@RequestMapping("/maintenance-records")
public class MaintenanceRecordsController {

    @Autowired
    IMaintenanceRecordsService imaintenanceRecordsService;

    @PostMapping("/admin/page10/selectpages")
    public Page<MaintenanceRecords> queryMaintenanceRecords(@RequestBody MaintenanceRecordsdto maintenanceRecordsdto) {

        return imaintenanceRecordsService.querypages(maintenanceRecordsdto);
    }

    /**
     *  批量删除
     */
    @DeleteMapping("/admin/page10/deleteusers")
    public void deletes(@RequestBody List<Integer> ids) {
        log.info("ids数组: {}", ids);
        imaintenanceRecordsService.deletes(ids);
    }

    /**
     * 单个删除
     */
    @DeleteMapping("/admin/page10/deleteuser")
    public void delete(@RequestBody MaintenanceRecordsdto maintenanceRecordsdto){
        Integer id = maintenanceRecordsdto.getMainmaintenanceRecordsId();
        System.out.println("ID是: " + id); // 添加日志
        if (id == null) {
            throw new IllegalArgumentException("ID不可以是null");
        }
        imaintenanceRecordsService.deleteuser(maintenanceRecordsdto.getMainmaintenanceRecordsId());
    }

    @PutMapping("/admin/page10/updaterecord")
    public void updaterecord(@RequestBody MaintenanceRecordsdto maintenanceRecordsdto){
    /*    try {
            log.info("更新记录：{}", maintenanceRecordsdto);
            imaintenanceRecordsService.update(maintenanceRecordsdto);
        } catch (Exception e) {
            log.error("更新记录时发生错误：", e);
            throw e; // 再次抛出异常以便前端可以捕捉到
        }*/
        imaintenanceRecordsService.update(maintenanceRecordsdto);
    }

    /**
     * 根据维修人员id查找自己的维修记录
     * @param employeeId
     * @return 自己的维修记录
     */
    @GetMapping("repair/getMaintenanceRecords/{employeeId}")
    public List<MaintenanceRecords> getMaintenanceRecords(@PathVariable Integer employeeId) {
        LambdaQueryWrapper<MaintenanceRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MaintenanceRecords::getEmployeeId, employeeId);

        // 使用 service 层的 list 方法
        return imaintenanceRecordsService.list(queryWrapper);
    }


    /**
     * 维修人员拆查询正在维修的记录
     * @param employeeId
     * @return
     */
    @GetMapping("repair/getNowMaintenanceRecords/{employeeId}")
    public List<MaintenanceRecords> getNowMaintenanceRecords(@PathVariable Integer employeeId){
        // 构建查询条件，查找当前正在维修的记录
        LambdaQueryWrapper<MaintenanceRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MaintenanceRecords::getEmployeeId, employeeId)
                .eq(MaintenanceRecords::getMaintenanceStatus, "正在维修");

        // 查询符合条件的维修记录（只会有一条记录）
        MaintenanceRecords maintenanceRecord = imaintenanceRecordsService.getOne(queryWrapper);

        // 如果没有找到记录，返回错误信息
        return imaintenanceRecordsService.list(queryWrapper);
    }


    /**
     * 维修人员上传维修照片并更新维修状态
     * @param files 上传的照片文件
     * @param employeeId 维修人员的ID
     * @return 更新后的维修记录
     */
    @PostMapping("repair/upMaintenanceRecords/{employeeId}")
    public ResponseEntity<ResponseResult> handleMaintenanceRecord(
            @RequestParam("files") MultipartFile[] files,
            @PathVariable Integer employeeId) {

        // 构建查询条件，查找当前正在维修的记录
        LambdaQueryWrapper<MaintenanceRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MaintenanceRecords::getEmployeeId, employeeId)
                .eq(MaintenanceRecords::getMaintenanceStatus, "正在维修");

        // 查询符合条件的维修记录（只会有一条记录）
        MaintenanceRecords maintenanceRecord = imaintenanceRecordsService.getOne(queryWrapper);

        // 如果没有找到记录，返回错误信息
        if (maintenanceRecord == null) {
            return ResponseEntity.badRequest().body(ResponseResult.fail("未找到正在维修的记录"));
        }

        // 判断是否有文件
        if (files == null || files.length == 0) {
            return ResponseEntity.badRequest().body(ResponseResult.fail("未上传任何文件"));
        }

        // 保存文件的本地目录
        String localDirectory = "E:/dev/nginx/html/repair/";

        StringBuilder completionPhotos = new StringBuilder();

        try {
            for (MultipartFile file : files) {
                // 获取文件名
                String originalFilename = file.getOriginalFilename();

                // 防止重名覆盖，使用系统时间戳加原始文件后缀
                String fileName = System.currentTimeMillis() + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

                // 创建目标文件对象
                File destFile = new File(localDirectory + fileName);

                // 确保目录存在
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }

                // 保存文件到本地
                file.transferTo(destFile);

                // 保存文件路径（这里保存的是文件在本地的路径）
                String fileUrl = "/repair/" + fileName;

                // 拼接所有文件的 URL
                if (completionPhotos.length() > 0) {
                    completionPhotos.append(",");
                }
                completionPhotos.append(fileUrl);
            }

            // 更新维修记录的状态和图片URL
            maintenanceRecord.setMaintenanceStatus("维修完毕");
            maintenanceRecord.setRepairDetails(maintenanceRecord.getTitle()+"维修完毕");
            maintenanceRecord.setRecordTime(new Date());
            maintenanceRecord.setRepairImage(completionPhotos.toString());

            // 更新数据库中的记录
            imaintenanceRecordsService.updateById(maintenanceRecord);

            // 返回成功响应
            return ResponseEntity.ok(new ResponseResult(200, "文件上传成功并更新维修记录", maintenanceRecord));
        } catch (IOException e) {
            e.printStackTrace();
            // 返回失败响应
            return ResponseEntity.status(500).body(ResponseResult.fail("文件上传或记录更新失败"));
        }
    }


    /**
     * 查询维修记录
     * */
    @PostMapping("/select_1/{userNo}/{evaStatus}")
    public List<MaintenanceRecords> select_1(@PathVariable Integer userNo,
                                             @PathVariable String evaStatus) {
        // 验证参数
        if (userNo == null || evaStatus == null) {
            return null;
        }
        List<MaintenanceRecords> list = imaintenanceRecordsService.select_1(userNo, evaStatus);
        return list;
    }

    /**
     * 将评价状态（eva_status）改为已评价
     */
    @PutMapping("/updateStatus/{maintenanceRecordsId}")
    public boolean updateStatus(@PathVariable Integer maintenanceRecordsId) {
        boolean result = imaintenanceRecordsService.updateStatus(maintenanceRecordsId);
        return result;
    }


    /**
     * 先查询出报修时间一样的维修记录和故障报修表对应插入对应一条维修记录
     * @param maintenanceRecordRequest
     * @return MaintenanceRecords
     */
    @PostMapping("/upBackData")
    public MaintenanceRecords getMaintenanceRecords(@RequestBody MaintenanceRecords maintenanceRecordRequest) {
        Integer userNo = maintenanceRecordRequest.getUserNo();
        Integer employeeId = maintenanceRecordRequest.getEmployeeId();
        String employeeName = maintenanceRecordRequest.getEmployeeName();

        System.out.println("---------------------------/////" + userNo + "///////////" + employeeId + employeeName);

        QueryWrapper<MaintenanceRecords> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_no", userNo)
                .isNull("employee_id"); // 查询 employee_id 为 null 的记录

        List<MaintenanceRecords> list = imaintenanceRecordsService.list(queryWrapper);
        log.info("getMaintenanceRecords: {}", list);

        // 检查 maintenanceRecords 是否为 null
        if (list == null || list.isEmpty()) {
            throw new RuntimeException("未找到对应的维修记录");
        }

        MaintenanceRecords maintenanceRecords = list.get(0);
        Date currentDate = new Date();

        // 创建一个 SimpleDateFormat 对象并指定日期格式
        SimpleDateFormat sdfb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 将 Date 对象转换为字符串
        String formattedDate = sdfb.format(currentDate);

        // 更新员工 id
        maintenanceRecords.setEmployeeId(employeeId);
        // 更新员工名字
        maintenanceRecords.setEmployeeName(employeeName);
        // 更新维修派工时间
        maintenanceRecords.setDispatchTime(formattedDate);
        // 更新维修状态
        maintenanceRecords.setMaintenanceStatus("待接受");
        // 更新记录时间（如果这个字段和 dispatchTime 不同，保留）
        maintenanceRecords.setRecordTime(new Date());
        // 更新更新时间
        maintenanceRecords.setUpdateTime(new Date());

        log.info("saveOrUpdate: {}", maintenanceRecords);

        boolean result = imaintenanceRecordsService.updateById(maintenanceRecords);
        if (!result) {
            throw new RuntimeException("更新维修记录失败");
        }

        return maintenanceRecords;
    }
}
